package com.uvstu.common.pay.utils;

import cn.uvtool.exception.TClientException;
import com.uvstu.common.pay.config.WxPayConfig;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @version V1.0
 * @Title: 微信退款携带证书工具类
 * @author: zhengweibin
 * @Description:
 * @create: 2022-12-02 23:01
 */
public class WxHttpUtil {

    /**
     * 创建带证书的实例
     * @return
     * @throws TClientException
     */
    public static CloseableHttpClient createSSLClientCert() throws TClientException {
        try {
            File file = new File(WxPayConfig.CERT_PATH);
            InputStream certStream = new FileInputStream(file);
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(certStream, WxPayConfig.CERT_PASSWORD.toCharArray());
            certStream.close();
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                public boolean isTrusted(X509Certificate[] chain,
                                         String authType) throws CertificateException {
                    return true;
                }
            }).loadKeyMaterial(keyStore, WxPayConfig.CERT_PASSWORD.toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,new String[]{"TLSv1","TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (Exception e) {
            throw new TClientException("微信支付退款携带证书错误！错误信息："+e.getMessage());
        }
    }


    /**
     * http POST 请求
     * @param  url:请求地址
     * @param  body: body实体字符串
     * @return
     */
    public static String httpPostReflect(String url, String body) throws TClientException {
        HttpClient client = createSSLClientCert();
        HttpPost httpost = new HttpPost(url);
        try {
            //所有请求的body都需采用UTF-8编码
            StringEntity entity = new StringEntity(body,"UTF-8");
            httpost.setEntity(entity);
            //支付平台所有的API仅支持JSON格式的请求调用，HTTP请求头Content-Type设为application/json
            httpost.addHeader("Content-Type","text/xml");
            HttpResponse response = client.execute(httpost);
            //所有响应也采用UTF-8编码
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            return result;
        }catch (Exception e) {
           throw new TClientException("微信退款请求失败！错误信息："+e.getMessage());
        }
    }


}
